import json
from PySide6 import QtCore
from PySide6.QtCore import Qt, QRegularExpression
from PySide6.QtWidgets import (QWidget, QGroupBox, QHBoxLayout, QMessageBox,
                             QVBoxLayout, QGridLayout)
from PySide6.QtGui import QIcon, QRegularExpressionValidator

from qfluentwidgets import CaptionLabel, LineEdit, PushButton
from core.maocr import maocr
from core.util import is_valid_email
from core.log import logger
import setting as c

class SFormSignup(QWidget):

    def __init__(self, parent):
        super().__init__()
        
        self.setWindowIcon(QIcon(c.icon_dir_path))
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        
        self.initUI()
        
        # 计算并设置新窗口的位置
        self.setGeometry(0, 0, 300, 230)
        self.move(parent.frameGeometry().topLeft() + parent.rect().center() - self.rect().center())
        
     # 绘制界面
    def initUI(self):
        
        self.CreateWindowCommbo()
        
        gridLayout = QGridLayout() 
        gridLayout.addWidget(self.vWinGroupBox, 0, 0, QtCore.Qt.AlignLeft)
        
        # 调用方法绘制界面
        self.setWindowTitle(c.WINTITLE)
        mainLayout = QHBoxLayout()
        mainLayout.addLayout(gridLayout)
        self.setLayout(mainLayout)
        
    def CreateWindowCommbo(self):
                
        self.vWinGroupBox = QGroupBox('sign up')
        self.vWinGroupBox.setMinimumSize(300, 340)
        
        regex = QRegularExpression("^[A-Za-z0-9]{0,16}$")
        validator = QRegularExpressionValidator(regex)
        self.username_le = LineEdit(self)
        self.username_label = CaptionLabel('用户名:', self)
        self.username_le.setPlaceholderText("输入用户名")
        self.username_le.setValidator(validator)
    
        regex = QRegularExpression("[A-Za-z0-9@.]{0,32}")
        validator = QRegularExpressionValidator(regex)
        self.email_le = LineEdit(self)
        self.email_label = CaptionLabel('Email:', self)
        self.email_le.setPlaceholderText("输入Email")
        self.email_le.setValidator(validator)
        
        regex = QRegularExpression("[A-Za-z0-9.]{0,16}")
        validator = QRegularExpressionValidator(regex)
        self.password_le = LineEdit(self)
        self.password_label = CaptionLabel('密码:', self)
        self.password_le.setPlaceholderText("输入密码")
        self.password_le.setValidator(validator)
        self.password_le.setEchoMode(LineEdit.Password) 
        
        self.password2_le = LineEdit(self)
        self.password2_label = CaptionLabel('确认密码:', self)
        self.password2_le.setPlaceholderText("再次输入密码")
        self.password2_le.setValidator(validator)
        self.password2_le.setEchoMode(LineEdit.Password) 
        
        self.invitated_le = LineEdit(self)
        self.invitated_label = CaptionLabel('邀请码:', self)
        self.invitated_le.setPlaceholderText("可选")
        self.invitated_le.setMaxLength(16)
        
        self.tips_label = CaptionLabel('', self)
        self.sign_up_btn = PushButton('完成', self)
        self.sign_up_btn.clicked.connect(self.onclick_sign_up)
        
        self.vBoxLayout = QVBoxLayout(self)
        
        self.hBoxLayout_username = QHBoxLayout()
        self.hBoxLayout_email = QHBoxLayout()
        self.hBoxLayout_password = QHBoxLayout()
        self.hBoxLayout_password2 = QHBoxLayout()
        self.hBoxLayout_invatation = QHBoxLayout()
        self.vBoxLayout_signup = QVBoxLayout()
    
        self.initLayout()
    
        self.vWinGroupBox.setLayout(self.vBoxLayout)
        
    def initLayout(self):
        
        self.hBoxLayout_username.setSpacing(10)
        self.hBoxLayout_username.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_username.addWidget(self.username_label, 1)
        self.hBoxLayout_username.addWidget(self.username_le, 4)
        
        self.hBoxLayout_email.setSpacing(10)
        self.hBoxLayout_email.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_email.addWidget(self.email_label, 1)
        self.hBoxLayout_email.addWidget(self.email_le, 4)
        
        self.hBoxLayout_password.setSpacing(10)
        self.hBoxLayout_password.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_password.addWidget(self.password_label, 1)
        self.hBoxLayout_password.addWidget(self.password_le, 4)
        
        self.hBoxLayout_password2.setSpacing(10)
        self.hBoxLayout_password2.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_password2.addWidget(self.password2_label, 1)
        self.hBoxLayout_password2.addWidget(self.password2_le, 4)
        
        self.hBoxLayout_invatation.setSpacing(10)
        self.hBoxLayout_invatation.setContentsMargins(5, 5, 3, 3)
        self.hBoxLayout_invatation.addWidget(self.invitated_label, 1)
        self.hBoxLayout_invatation.addWidget(self.invitated_le, 4)
        
        self.vBoxLayout_signup.setSpacing(10)
        self.vBoxLayout_signup.setContentsMargins(5, 5, 3, 3)
        self.vBoxLayout_signup.addWidget(self.sign_up_btn)
        self.vBoxLayout_signup.addWidget(self.tips_label)
        
        self.vBoxLayout.addLayout(self.hBoxLayout_username)
        self.vBoxLayout.addLayout(self.hBoxLayout_email)
        self.vBoxLayout.addLayout(self.hBoxLayout_password)
        self.vBoxLayout.addLayout(self.hBoxLayout_password2)
        self.vBoxLayout.addLayout(self.hBoxLayout_invatation)
        self.vBoxLayout.addLayout(self.vBoxLayout_signup)
        
    
    def closeEvent(self, event):
            
        # 调用父类的closeEvent方法，确保窗口能够正常关闭
        super().closeEvent(event)
    
    def Reset(self):
        self.username_le.clear()
        self.email_le.clear()
        self.password_le.clear()
        self.password2_le.clear()
        self.invitated_le.clear()
        self.tips_label.clear()
    
    def setTips(self, tips):
        self.tips_label.setText(f"<font color='red'>{tips}</font>")
    
    
    def onclick_sign_up(self):
        username = self.username_le.text()
        email = self.email_le.text()
        password = self.password_le.text()
        password2 = self.password2_le.text()
        
        self.setTips("")
        if len(username) < 5:
            tips = "用户名至少需要5个字符"
            self.setTips(tips)
            return
        
        if len(email) == 0:
            tips = "请输入Email"
            self.setTips(tips)
            return
        
        if not is_valid_email(email):
            tips = "Email 格式错误"
            self.setTips(tips)
            return
        
        if password != password2:
            tips = "两次密码不一致"
            self.setTips(tips)
            return
        if len(password) < 8:
            tips = "密码至少需要8个字符"
            self.setTips(tips)
            return
        
        invitated = self.invitated_le.text()
        
        res, ok = maocr.signup(username, email, password, invitated)
        if not ok:
            tips = "网络错误"
            self.setTips(tips)
            return
        try:
            info = json.loads(res)
        except json.JSONDecodeError:
            logger.error(f"wrong json format: {res} ") 
            return 
        logger.info(info)
        if info['message'] != "":
            self.setTips(info['message'])
            return
        QMessageBox.information(self, "消息", "注册成功") 
        self.close()
        
        
        